const jwt = require('jsonwebtoken');
const User = require('../models/User');

// JWT 认证中间件
const authenticate = async (req, res, next) => {
  try {
    // 从请求头中获取 token
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: 'Authentication token not provided'
      });
    }
    
    // 提取 token
    const token = authHeader.split(' ')[1];
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: 'Authentication token not provided'
      });
    }
    
    try {
      // 验证 token
      const decoded = jwt.verify(token, process.env.JWT_SECRET || 'default-secret-key');
      
      // 查找用户
      const user = await User.findOne({ 
        where: { id: decoded.userId }
      });
      
      if (!user) {
        return res.status(401).json({
          success: false,
          message: 'User does not exist'
        });
      }
      
      // 将用户信息附加到请求对象
      req.user = user;
      req.userId = decoded.userId;
      
      next();
    } catch (error) {
      if (error.name === 'JsonWebTokenError') {
        return res.status(401).json({
          success: false,
          message: 'Invalid authentication token'
        });
      }
      
      if (error.name === 'TokenExpiredError') {
        return res.status(401).json({
          success: false,
          message: 'Authentication token has expired'
        });
      }
      
      throw error;
    }
  } catch (error) {
    console.error('Authentication middleware error:', error);
    return res.status(500).json({
      success: false,
      message: 'Authentication failed'
    });
  }
};

// 生成 JWT token
const generateToken = (userId) => {
  return jwt.sign(
    { userId },
    process.env.JWT_SECRET || 'default-secret-key',
    { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
  );
};

module.exports = {
  authenticate,
  generateToken
};
